<template>
  <div class="seller-edit">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商户' : '新增商户'"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="seller-form"
      >
        <!-- 基本信息部分 -->
        <h3 class="form-section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择商户状态" style="width: 100%">
                <el-option label="正常" value="1" />
                <el-option label="禁用" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户评分" prop="score">
              <el-rate v-model="form.score" allow-half :max="5" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商户地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入商户地址" />
        </el-form-item>

        <!-- 图片上传部分 -->
        <h3 class="form-section-title">图片信息</h3>
        <el-form-item label="商家主图" prop="image">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadMainImage"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传比例为1:1的图片，大小不超过2MB</div>
        </el-form-item>

        <el-form-item label="商家相册" prop="gallery">
          <el-upload
            class="gallery-uploader"
            action="#"
            :http-request="uploadGalleryImage"
            list-type="picture-card"
            :file-list="galleryFileList"
            :before-upload="beforeImageUpload"
            @remove="handleGalleryRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传6张图片，每张大小不超过2MB</div>
        </el-form-item>

        <!-- 营业信息部分 -->
        <h3 class="form-section-title">营业信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="form.businessHours" placeholder="例如：09:00-22:00" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送时间" prop="deliveryTime">
              <el-input v-model="form.deliveryTime" placeholder="例如：09:00-21:00" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="工作时间设置" prop="workingHours">
          <el-input v-model="form.workingHours" placeholder="例如：周一至周日 09:00-22:00" />
        </el-form-item>

        <el-form-item label="商家简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入商家简介"
          />
        </el-form-item>

        <!-- 配送员信息 -->
        <h3 class="form-section-title">配送员信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="配送员姓名" prop="deliveryStaff.name">
              <el-input v-model="form.deliveryStaff.name" placeholder="请输入配送员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送员电话" prop="deliveryStaff.phone">
              <el-input v-model="form.deliveryStaff.phone" placeholder="请输入配送员电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他信息部分 -->
        <h3 class="form-section-title">其他信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入驻时间" prop="joinTime">
              <el-date-picker
                v-model="form.joinTime"
                type="date"
                placeholder="选择入驻时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在售商品数量" prop="onSaleProductCount">
              <el-input-number
                v-model="form.onSaleProductCount"
                :min="0"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单总金额" prop="totalOrderAmount">
              <el-input-number
                v-model="form.totalOrderAmount"
                :min="0"
                :precision="2"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货总金额" prop="totalRefundAmount">
              <el-input-number
                v-model="form.totalRefundAmount"
                :min="0"
                :precision="2"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="平台分润" prop="totalPlatformProfit">
              <el-input-number
                v-model="form.totalPlatformProfit"
                :min="0"
                :precision="2"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
});

const emit = defineEmits(['update:visible', 'submit', 'cancel']);

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 是否为编辑模式
const isEdit = computed(() => !!props.editData);

// 表单引用
const formRef = ref(null);

// 表单数据
const form = reactive({
  name: '',
  image: '',
  score: 5,
  address: '',
  contact: '',
  deliveryTime: '',
  deliveryStaff: {
    name: '',
    phone: ''
  },
  introduction: '',
  businessHours: '',
  workingHours: '',
  gallery: [],
  joinTime: '',
  totalOrderAmount: 0,
  totalRefundAmount: 0,
  totalPlatformProfit: 0,
  onSaleProductCount: 0,
  status: '1'
});

// 相册文件列表
const galleryFileList = ref([]);

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入商户地址', trigger: 'blur' }],
  image: [{ required: true, message: '请上传商户主图', trigger: 'change' }],
  status: [{ required: true, message: '请选择商户状态', trigger: 'change' }],
  businessHours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }],
  deliveryTime: [{ required: true, message: '请输入配送时间', trigger: 'blur' }],
  'deliveryStaff.name': [{ required: true, message: '请输入配送员姓名', trigger: 'blur' }],
  'deliveryStaff.phone': [
    { required: true, message: '请输入配送员电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
});

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  // 重置为初始值
  Object.assign(form, {
    name: '',
    image: '',
    score: 5,
    address: '',
    contact: '',
    deliveryTime: '',
    deliveryStaff: {
      name: '',
      phone: ''
    },
    introduction: '',
    businessHours: '',
    workingHours: '',
    gallery: [],
    joinTime: '',
    totalOrderAmount: 0,
    totalRefundAmount: 0,
    totalPlatformProfit: 0,
    onSaleProductCount: 0,
    status: '1'
  });
  
  galleryFileList.value = [];
};

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      // 编辑模式，填充表单数据
      Object.keys(form).forEach(key => {
        if (key === 'deliveryStaff') {
          form.deliveryStaff.name = newVal.deliveryStaff?.name || '';
          form.deliveryStaff.phone = newVal.deliveryStaff?.phone || '';
        } else if (key === 'gallery') {
          form.gallery = [...(newVal.gallery || [])];
          galleryFileList.value = (newVal.gallery || []).map((url, index) => ({
            name: `图片${index + 1}`,
            url
          }));
        } else {
          form[key] = newVal[key] !== undefined ? newVal[key] : form[key];
        }
      });
    } else {
      // 新增模式，重置表单
      resetForm();
    }
  },
  { immediate: true, deep: true }
);

// 关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      dialogVisible.value = false;
      emit('cancel');
      resetForm();
    })
    .catch(() => {
      // 取消关闭
    });
};

// 图片上传前的检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  
  return true;
};

// 上传商家主图
const uploadMainImage = (options) => {
  // 这里应该调用实际的上传API，这里用FileReader模拟
  const reader = new FileReader();
  reader.readAsDataURL(options.file);
  reader.onload = () => {
    form.image = reader.result;
    // 实际项目中这里应该是上传成功后的图片URL
    ElMessage.success('主图上传成功');
  };
};

// 上传相册图片
const uploadGalleryImage = (options) => {
  // 这里应该调用实际的上传API，这里用FileReader模拟
  if (form.gallery.length >= 6) {
    ElMessage.warning('最多上传6张相册图片');
    return;
  }

  const reader = new FileReader();
  reader.readAsDataURL(options.file);
  reader.onload = () => {
    const imageUrl = reader.result;
    form.gallery.push(imageUrl);
    galleryFileList.value.push({
      name: options.file.name,
      url: imageUrl
    });
    // 实际项目中这里应该是上传成功后的图片URL
    ElMessage.success('相册图片上传成功');
  };
};

// 移除相册图片
const handleGalleryRemove = (file) => {
  const index = galleryFileList.value.findIndex(item => item.url === file.url);
  if (index !== -1) {
    galleryFileList.value.splice(index, 1);
    form.gallery.splice(index, 1);
  }
};

// 提交表单
const submitForm = () => {
  if (!formRef.value) return;
  
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单数据
      const submitData = {
        ...form,
        // 可以在这里对数据进行处理，例如格式化日期等
        joinTime: form.joinTime ? new Date(form.joinTime).toISOString().split('T')[0] : ''
      };
      
      emit('submit', submitData);
      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功');
      dialogVisible.value = false;
      resetForm();
    } else {
      ElMessage.error('请填写必填项');
      return false;
    }
  });
};
</script>

<style scoped lang="scss">
.seller-edit {
  .seller-form {
    max-height: 65vh;
    overflow-y: auto;
    padding: 0 15px;
  }
  
  .form-section-title {
    margin: 20px 0 15px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;
    color: #409EFF;
  }
  
  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }
  
  .upload-tip {
    font-size: 12px;
    color: #606266;
    margin-top: 5px;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style>
